import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Home.vue')
    }, {
      path: '/login',
      component: () => import('@/views/Login.vue')
    }, {
      path: '/register',
      component: () => import('@/views/Register.vue')
    }, 
    {
      path: '/headerNav',
      component: () => import('@/components/HeaderNav.vue')
    }, {
      path: '/shopcart',
      component: () => import('@/views/Shopcart.vue')
    },
    {
      path: '/confirmOrder',
      component: () => import('@/views/ConfirmOrder.vue')
    },
    {
      path: '/search',
      name: 'SearchResults',
      component: () => import('@/views/SearchResults.vue')
    },
    {
      path: '/booksDetails',
      name: 'BooksDetails',
      component: () => import('@/views/BooksDetails.vue')
    },
    {
      path: '/booksDetails/:id',
      name: 'BookDetailsWithId',
      component: () => import('@/views/BooksDetails.vue')
    },
    {
      path: '/order',
      component: () => import('@/views/Order.vue')
    },
    {
      path: '/order/:id',
      name: 'OrderDetail',
      component: () => import('@/views/OrderDetail.vue')
    },
    {
      path: '/own',
      component: () => import('@/views/Own.vue')
    },
    {
      path: '/topicBlock/:index',  /* 给参数占位,?是以防不传的时候 */
      component: () => import('@/views/TopicBlock.vue'),
      props:true
    }
  ],
})

//导航守卫
router.beforeEach((to, from, next) => {
  //需要登录才能访问的路径
  var loginUrl = ['/shopcart', '/confirmOrder', '/order', '/order/:id']
  if (loginUrl.includes(to.path) || to.path.startsWith('/order/')) {
    //判断是不是登录
    if (sessionStorage.getItem('token')) {
      next()
    } else {
      alert('请先登录')
      next('/login')
    }
  } else {
    next()
  }
})

export default router
